package cn.pojo.code;

import cn.entity.AccessToken;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.util.Wechat;
import com.alibaba.fastjson.JSONObject;
import javax.imageio.stream.FileImageOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class Temporary {

    private static final String TEMPORARY_QR_CODE = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";

    private static final String TICKET = "https://mp.weixin.qq.com/cgi-bin/showqrcode";

    /**
     * 生成公众号二维码
     * @param args
     * @throws UnsupportedEncodingException
     */
    public static void main(String[] args) throws UnsupportedEncodingException {

        String appId = "wx28f50c8a08e5468b";
        String appSecret = "27b2530f39b240763642405e4a033cdb";
        AccessToken accessToken = Wechat.getToken(appId, appSecret);

        String url = TEMPORARY_QR_CODE.replace("TOKEN",accessToken.getAccess_token());
        String param = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"test\"}}}";
        String post = HttpUtil.post(url,param);
        System.out.println(post);

        JSONObject jsonObject = JSONObject.parseObject(post);
        Object ticket1 = jsonObject.get("ticket");
        String encode = URLEncoder.encode(ticket1.toString());
        HttpResponse execute = HttpRequest.get(TICKET+"?ticket="+encode).execute();
        System.out.println("---------------------");

        FileImageOutputStream imageOutput = null;//打开输入流
        try {
            imageOutput = new FileImageOutputStream(new File("G:\\qrCode.png"));
            imageOutput.write(execute.bodyBytes(), 0, execute.bodyBytes().length);//将byte写入硬盘
            imageOutput.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(new String(execute.bodyBytes()));
    }
}
